const express = require('express');
const path = require('path');
const cookieParser = require('cookie-parser');
const bodyParser = require('body-parser');
const cors = require('cors');
const exec = require('child_process');
const app = express();

let processArr = [];
// 下面这两句话一定要写，是配置解析客户端请求所带的参数的
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: true }));
// app.use(cors);

app.all('*', (req, res, next) => {
  res.header("Access-Control-Allow-Origin", "*");
  res.header('Content-Type', 'text/plain');
  res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
  next();
});

app.all('/video', (req, res) => {
  if (req.method == "POST") {
    var param = req.body;
    if (processArr.length>0) {
      const child = processArr[0];
      child.disconnect();
      child.kill();
      if(child.killed){
        processArr.pop();
      }
    }
    let child_pro = exec.fork('./service.js');
    console.log(child_pro.pid);
    child_pro.send({"message":"hello"});
    processArr.push(child_pro);
    setTimeout(() => {
      res.end(JSON.stringify({ mess: 'success' }));
    }, 5000);

  } else {
    var param = req.query || req.params;
  }

});
app.listen(8126);
console.log('Server running at http://127.0.0.1:8125/');
module.exports = app;